<script setup lang="ts">
import { onMounted, ref } from 'vue'
import type { LoginForm, LoginRequest, LoginResponse } from '@/type/Auths'
import { useRouter } from 'vue-router'
import { loginApi, currentUserInfoApi } from '@/api/auth'
import type { ResultData } from '@/api/service'
import { useAuthStore } from '@/stores/auth'
import { routeMenuApi } from '@/api/menu'
import type { RouteMenu } from '@/type/Menu'
import { useMenuStore } from '@/stores/menu'
import type { UserVo } from '@/type/User'

const router = useRouter()
const { setToken, setUserInfo, accessToken } = useAuthStore()
const { setDynamic } = useMenuStore()

/* 登录表单绑定 */
const form = ref<LoginForm>({ password: '', username: '' })

onMounted(() => {
  // 当前为登录状态时跳转至主页面
  if (accessToken !== null) {
    router.push('/')
  }
})

/* 登录方法 */
function doLogin() {
  const param: LoginRequest = {
    username: form.value.username,
    password: form.value.password
  }

  loginApi(param)
    .then((response: ResultData<LoginResponse>) => {
      // 1. 设置 token
      setToken(response.data.tokenValue)
      // 2. 获取当前用户的详细信息, 存入pinia
      currentUserInfoApi().then((response: ResultData<UserVo>) => {
        setUserInfo(response.data)
      })
      // 3. 调用路由菜单接口获取当前用户的菜单
      routeMenuApi().then((response: ResultData<RouteMenu[]>) => {
        setDynamic(response.data)
        // 使用 nextTick 确保状态更新后再跳转
          router.push('/')
      })
    })
    .catch(() => {
      // 登录失败时，跳转至登陆页面
      router.push('/login')
    })
}
</script>

<template>
  <el-card class="saber-login saber-card">
    <h1 class="saber-title">SABER</h1>
    <el-form :model="form" class="saber-form">
      <el-form-item>
        <el-input v-model="form.username" placeholder="用户" />
      </el-form-item>
      <el-form-item>
        <el-input v-model="form.password" type="password" placeholder="密码" />
      </el-form-item>
      <el-form-item style="width: 100%">
        <el-button style="width: 100%" type="primary" @click="doLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<style scoped>
.saber-login {
  width: 300px;
  margin: 120px auto;
  background-color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.saber-title {
  color: white;
  text-align: center;
  text-shadow:
    2px 2px 0 rgb(64, 158, 255),
    0 0 0 blue;
}

.saber-form {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
</style>
